package com.iot08.api.response;

import com.iot08.api.exception.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import java.util.Arrays;

/**
 * @version 1.0
 * @Description:
 * @time: 2020/12/23 9:41
 * @author: Rock
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class ValidateParam {

    //切点
    @Pointcut("execution(public * com.iot08.api.controller..*.*(..))")
    public void cutService() {

    }

    @Around("cutService()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            Arrays.stream(args)
                    .forEach(arg -> {
                        if (arg instanceof BindingResult) {
                            BindingResult result = (BindingResult) arg;
                            if (result.hasErrors() && result.getAllErrors().size() > 0) {
                                String msg = result.getAllErrors().get(0).getDefaultMessage();
                                log.warn("param exception msg={} target={}", msg, result.getTarget());
                                throw new ServerException(msg, false);
                            }
                        }
                    });
        }
        return joinPoint.proceed();
    }

}
